package com.xuecheng.media.service.impl;

import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.MediaDto;
import com.xuecheng.commons.model.dto.MediaQueryDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.VodUploadDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mappers.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-21
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    VodTemplate vodTemplate;

    //上传 + 刷新
    //获取阿里云上传凭证
    @Override
    public ResponseResult createToken(VodUploadDto dto) throws Exception {
        String title = dto.getTitle();
        String fileName = dto.getFileName();
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(fileName)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //调用vodTemplate方法，获取上传凭证
        CreateUploadVideoResponse response = vodTemplate.createUploadVideo(title, fileName);
        //构造返回
        VodUploadVo vo = new VodUploadVo();
        vo.setVideoId(response.getVideoId());
        vo.setUploadAddress(response.getUploadAddress());
        vo.setUploadAuth(response.getUploadAuth());
        vo.setRequestId(response.getRequestId());
        vo.setUserId(AuthInfoHolder.getUserId().toString());
        return ResponseResult.okResult(vo);
    }

    //更新阿里云上传凭证
    @Override
    public ResponseResult refreshToken(String videoId) throws Exception {
        //调用工具类，刷新凭证获取响应
        RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
        //构造返回
        VodUploadVo vo = new VodUploadVo();
        vo.setVideoId(response.getVideoId());
        vo.setUploadAddress(response.getUploadAddress());
        vo.setUploadAuth(response.getUploadAuth());
        vo.setRequestId(response.getRequestId());
        vo.setUserId(AuthInfoHolder.getUserId().toString());
        return ResponseResult.okResult(vo);
    }

    //保存媒资
    @Override
    public ResponseResult saveMedia(MediaDto dto) throws Exception {
        //1.创建实体类对象Media
        Media media = BeanHelper.copyProperties(dto, Media.class);
        //2.设置基本参数
        media.setCompanyName(AuthInfoHolder.getAuthInfo().getCompanyName());
        media.setCreateDate(new Date());
        media.setStatus(CommonConstants.USING_FLAG.toString());
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS);
        //3.设置阿里云参数.查询阿里云视频的详情
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(dto.getFileId());
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList(); //媒资播放信息
        GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);           //获取对象
        String duration = playInfo.getDuration();   //时长
        String playURL = playInfo.getPlayURL();     //播放地址
        media.setTimelength(duration);
        media.setUrl(playURL);
        //4.保存
        boolean save = this.save(media);
        if (!save) {
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        //5.返回
        return ResponseResult.okResult();
    }

    //查询媒资
    @Override
    public ResponseResult findMediaList(PageRequest request, MediaQueryDto dto) {
        //1.构造分页页面对象
        Page<Media> pageParam = new Page<>(request.getPageNo(),request.getPageSize());
        //2.构造查询条件
        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(dto.getFilename())) {
            qw.like(Media::getFilename,"%" + dto.getFilename() + "%");
        }
        if (!StringUtils.isEmpty(dto.getAuditStatus())) {
            qw.eq(Media::getAuditStatus,dto.getAuditStatus());
        }
        if (!StringUtils.isEmpty(dto.getType())) {
            qw.eq(Media::getType,dto.getType());
        }
        //使用状态
        qw.eq(Media::getStatus,CommonConstants.USING_FLAG);
        //3.分页查询
        IPage<Media> page = this.page(pageParam, qw);
        //4.构造自己的id返回
        List<Media> list = page.getRecords();
        List<MediaVo> vos = BeanHelper.copyWithCollection(list, MediaVo.class);
        return PageResponseResult.okResult(page.getTotal(),vos);
    }

    //根据媒资id获取播放连接
    @Override
    public ResponseResult previewMediaById(Long mediaId) throws Exception {
        //数据库地址有时效性。应该是根据我们数据库表里的fileId从阿里云查询
        Media media = this.getById(mediaId);
        String fileId = media.getFileId();
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(fileId);
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo playInfo  = playInfoList.get(0);
        String playURL = playInfo.getPlayURL();
        return ResponseResult.okResult(playURL);
    }

    //根据id删除媒资信息(逻辑删除)
    @Override
    public ResponseResult deleteMediaById(Long mediaId) {
        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();
        qw.eq(Media::getId,mediaId);
        boolean remove = this.remove(qw);
        if (!remove) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        return ResponseResult.okResult(remove);
    }

    //根据id获取媒资的播放地址
    @Override
    public ResponseResult<ResourceVo> findMediaUrl(Long mediaId) throws Exception {
        //根据id查询媒资表中的数据，获取阿里云视频id
        Media media = this.getById(mediaId);
        String fileId = media.getFileId();  //阿里云视频的id
        //调用阿里云工具，获取播放地址
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(fileId);
        //解析响应第地址
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);
        String playURL = playInfo.getPlayURL();
        //构造返回
        ResourceVo vo = new ResourceVo();
        vo.setPlayUrl(playURL);
        return ResponseResult.okResult(vo);
    }
}
